package com.cloudlinkscm.base.filecenter.controller;

import com.cloudlinkscm.base.filecenter.model.bo.DownloadResponseBo;
import com.cloudlinkscm.base.filecenter.model.dto.DeleteRequestDto;
import com.cloudlinkscm.base.filecenter.model.dto.DocumentUploadDto;
import com.cloudlinkscm.base.filecenter.model.dto.DownloadRequestDto;
import com.cloudlinkscm.base.filecenter.model.dto.ImageUploadDto;
import com.cloudlinkscm.base.filecenter.service.FileRemoteService;
import com.cloudlinkscm.base.filecenter.service.FileService;
import com.cloudlinkscm.loms.framework.core.pojo.RestfulApiResponse;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : tac
 * @date : 2017/7/21
 */

@RequestMapping(FileRemoteService.PATH)
@RestController
public class FileController implements FileRemoteService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @ApiOperation("批量下载文档")
    @Override
    public RestfulApiResponse<Map<String, String>> documentUrls(DownloadRequestDto dto) {
        Map<String, String> urlMap = new HashMap<>();
        Map<String, String> streamMap = fileService.documentStreamIds(dto.getFileIds());
        streamMap.forEach((fileId, streamId) -> urlMap.put(fileId, buildDownloadUrl(streamId)));
        return RestfulApiResponse.success("获取下载url成功", urlMap);
    }

    @ApiOperation(value = "批量下载图片", hidden = true)
    @Override
    public RestfulApiResponse<Map<String, String>> imageUrls(DownloadRequestDto dto) {
        return RestfulApiResponse.success("获取下载url成功", fileService.downloadImages(dto.getFileIds()));
    }

    @ApiOperation("上传文档")
    @Override
    public RestfulApiResponse<String> uploadDocument(@ApiParam(value = "要上传的文件", required = true) @RequestParam MultipartFile file, DocumentUploadDto args) {
        return RestfulApiResponse.success("上传文档成功", fileService.uploadDocument(file, args));
    }

    @ApiOperation(value = "上传图片", hidden = true)
    @Override
    public RestfulApiResponse<String> uploadImage(@ApiParam(value = "要上传的图片", required = true) @RequestParam MultipartFile file, ImageUploadDto args) {
        return RestfulApiResponse.success("上传图片成功", fileService.uploadImage(file, args));
    }

    @ApiOperation(value = "批量删除文件")
    @Override
    public RestfulApiResponse<Integer> delete(DeleteRequestDto dto) {
        return RestfulApiResponse.success("删除文件成功", fileService.delete(dto));
    }

    @RequestMapping(value = DOWNLOAD_ACTION + "/{streamId}", method = RequestMethod.GET)
    @ApiOperation("获取指定文件流")
    public void download(@ApiParam(value = "文件流id", required = true) @PathVariable("streamId") String streamId, HttpServletResponse response) {
        DownloadResponseBo bo = fileService.download(streamId);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition",
                "attachment;fileName=" + bo.getFileStream().getFileName());
        byte[] buffer = new byte[1024];
        FileInputStream fis = (FileInputStream) bo.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(fis);
        try {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            logger.error("写io流异常", e);
            throw new RuntimeException(e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String buildDownloadUrl(String streamId) {
        return FileRemoteService.PATH + "/" + FileRemoteService.DOWNLOAD_ACTION + "/" + streamId;
    }
}
